package cc.iotkit.data.service;

import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.dao.DeviceHourlyReportRepository;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.manager.IDeviceHourlyReportData;
import cc.iotkit.data.manager.IDeviceHourlyReportData;
import cc.iotkit.data.model.TbDeviceHourlyReport;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.device.DeviceHourlyReport;
import cc.iotkit.model.device.DeviceHourlyReport;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static cc.iotkit.data.model.QTbDeviceHourlyReport.tbDeviceHourlyReport;

@Primary
@Service
public class DeviceHourlyReportDataImpl implements IDeviceHourlyReportData, IJPACommData<DeviceHourlyReport, Long> {
    private static Logger logger = LoggerFactory.getLogger(DeviceHourlyReportDataImpl.class);
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private DeviceHourlyReportRepository repository;

    @Override
    public JpaRepository getBaseRepository() {
        return repository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbDeviceHourlyReport.class;
    }

    @Override
    public Class getTClass() {
        return DeviceHourlyReport.class;
    }


    //@Transactional(rollbackFor = Exception.class)
    public void batchSave(List<DeviceHourlyReport> data) {
        // 创建日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<TbDeviceHourlyReport> list=new ArrayList<>();
        data.forEach(d->{
            synchronized (this) {
                String deviceId = d.getDeviceId();
                // 格式化日期
                //String formattedDate =sdf.format(d.getReportDate());
                TbDeviceHourlyReport row = repository.findFirstByReportDateAndDeviceId(sdf.format(d.getReportDate()),d.getHour(), deviceId);

                if (row != null) {
                    if (d.getOnlineTimes() != null)
                        row.setOnlineTimes(d.getOnlineTimes());
                    if (d.getDistance() != null)
                        row.setDistance(d.getDistance());
                    row.setSquare(d.getSquare());
                } else {
                    //list.add(MapstructUtils.convert(d,TbDeviceHourlyReport.class));
                    row = MapstructUtils.convert(d, TbDeviceHourlyReport.class);
                }
                logger.info("HourlyReportInsert:"+ JSONUtil.toJsonStr(row));
                row.setDts(new DateTime());
                repository.save(row);
            }
        });
    }
    private Predicate buildPredicate(DeviceHourlyReport data) {
        return PredicateBuilder.instance()
                .and(data.getId()!=null,()->tbDeviceHourlyReport.id.eq(data.getId()))
               .and(data.getDeviceId()!=null, () -> tbDeviceHourlyReport.deviceId.eq(data.getDeviceId()))
            .build();
    }


    public List<DeviceHourlyReport> findByConditions(DeviceHourlyReport record) {
        List<DeviceHourlyReport> rets=jpaQueryFactory.select(Projections.bean(DeviceHourlyReport.class,
                        tbDeviceHourlyReport.id))
                .from(tbDeviceHourlyReport)
                .where(buildPredicate(record)).fetch();
        return rets;
    }


}
